<?php
class G {
	
	protected static $oss;
	
    public static function http404 ($msg="...") {
        header("HTTP/1.1 404 Not Found");
        die($msg);
    }

    public static function http301 ($url="/") {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: $url");
        exit();
    }
	
	public static function http_js () {
		header('Content-Type: application/x-javascript; charset=utf-8');
	}
	
	public static function http_json () {
		header('Content-Type: Content-type: application/json; charset=utf-8');
	}
	
	public static function http_http () {
		header('Content-Type: text/html; charset=utf-8');
	}
	
	public static function byte_format ($size, $dec = 2) {
		if ($size < 0) {
			return false;
		}
		$end_fix = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
		$pos = 0;
		while ($size >= 1024) {
			$size /= 1024;
			$pos++;
		}
		return round($size, $dec) . ' ' . $end_fix[$pos];
	}
	
	public  static function my_exec ($cmd, $input = '') {
		$proc = proc_open($cmd, array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w')), $pipes);
		fwrite($pipes [0], $input);
		fclose($pipes [0]);
		$stdout = stream_get_contents($pipes [1]);
		fclose($pipes [1]);
		$stderr = stream_get_contents($pipes [2]);
		fclose($pipes [2]);
		$rtn = proc_close($proc);
		return array(
				'stdout' => $stdout,
				'stderr' => $stderr,
				'return' => $rtn
		);
	}
	
	public static function parse_apk ($filename, $rtn_txt = false) {
		$rtn = array();
		$command = AAPT_PATH . ' d badging ' . $filename;
		$std = self::my_exec($command);
		if ($std['return'] !== 0) {
			$error_file = '/tmp/zm.parse_apk.error.' . microtime(true);
			file_put_contents($error_file, print_r($std, true));
			trigger_error('Parse APK failed! Error file: '.$error_file, E_USER_WARNING);
		}
		if ($rtn_txt) {
			$rtn['txt'] = $std['stdout'];
		}
		//packageName, versionCode, versionName
		preg_match("%package: name='(.+)' versionCode='(.*)' versionName='(.*)'%U", $std['stdout'], $m );
		if (count($m ) == 4) {
			$rtn ['package_name'] = $m [1];
			$rtn ['ver_code'] = $m [2];
			$rtn ['ver_name'] = $m [3];
		}
		//sdkVersion
		preg_match("%sdkVersion:'(.+)'%U", $std['stdout'], $m );
		if (count($m ) == 2) {
			$rtn ['min_sdk_ver'] = $m [1];
		}
		//label, icon
		preg_match("%application: label='(.+)' icon='(.+)'%U", $std['stdout'], $m );
		if (count($m ) == 3) {
			$rtn ['icon'] = $m [2];
			$rtn ['name'] = $m [1];
		}
		//supportsScreens
		preg_match("%supports-screens:(.+)%", $std['stdout'], $m );
		if (isset($m [1] ) && $m [1] != '') {
			preg_match_all("%'(.+)'%U", $m [1], $m2 );
			if (isset($m2 [1] ) && is_array($m2 [1] ) && count($m2 [1] > 0 )) {
				$rtn ['screens_type'] = $m2 [1];
			}
		}
		//locales
		preg_match("%locales:(.+)%", $std['stdout'], $m );
		if (isset($m [1] ) && $m [1] != '') {
			preg_match_all("%'(.+)'%U", $m [1], $m2 );
			if (isset($m2 [1] ) && is_array($m2 [1] ) && count($m2 [1] > 0 )) {
				$rtn ['locales'] = $m2 [1];
				foreach($rtn ['locales'] as $k => $v ) {
					if ($v == '--_--') {
						$rtn ['locales'] [$k] = 'zh_CN';
					}
				}
				$rtn ['locales'] = array_unique($rtn ['locales'] );
			}
		}
		return $rtn;
	}
	
	public static function get_apk_icon ($filename) {
		$apk_info = G::parse_apk($filename);
		if (!$apk_info) return null;
		$icon_file_name = $apk_info['icon'];
		$zip = zip_open($filename);
		do {
			$entry = zip_read($zip);
		} while ($entry && zip_entry_name($entry) != $icon_file_name);
		zip_entry_open($zip, $entry, 'r');
		$icon = zip_entry_read($entry, zip_entry_filesize($entry));
		zip_entry_close($entry);
		zip_close($zip);
		return array('name' => basename($icon_file_name), 'body' => $icon);
	}
	
    public static function get_token($str, $time, $key) {
        if ($time < time() - 7 * 24 * 3600) {
            return false;
        }    
        return md5($str . ',' . $time . ',' . $key );
    }

    public static function is_sudo_user() {
        $user_token = isset($_COOKIE ['login_user_token_sudo'] ) ? trim($_COOKIE ['login_user_token_sudo'] ) : '';
        $user_token = $user_token == '' && isset($_POST ['login_user_token']) ? $_POST ['login_user_token'] : $user_token;
        list($token, $login_time, $user_id ) = array_pad(explode(',', $user_token ), 3, '' );
        if ($token != G::get_token($user_id, $login_time, _COOKIE_TOKEN_KEY ) || ! in_array($user_id, explode(',', _SUDO_USER_IDS ) )) { 
            return false;
        }    
        return intval($user_id);
    }

    public static function check_user () {
        $user_token = isset($_COOKIE ['login_user_token'] ) ? trim($_COOKIE ['login_user_token'] ) : '';
        $user_token = $user_token == '' && isset($_POST ['login_user_token']) ? $_POST ['login_user_token'] : $user_token;
        list($token, $login_time, $user_id ) = array_pad(explode(',', $user_token ), 3, '' );
        if ($token != G::get_token($user_id, $login_time, _COOKIE_TOKEN_KEY )) {
            return false;
        }
        return intval($user_id);
    }
    
    public static function get_host ($host = null) {
        if (!$host) $host = $_SERVER['HTTP_HOST'];
        $scheme = 'http';
        return "{$scheme}://{$host}";
    }
    
    public static function cookie ($key, $value = null, $expire = null) {
        if ($value === null) return isset($_COOKIE[$key]) ? $_COOKIE[$key] : null;
        setcookie($key, $value, $expire, '/');
    }
    
    public static function downloadHeader ($file_name, $content_length) {
		$filename = basename($file_name);
		$encoded_filename = urlencode($filename);
		$encoded_filename = str_replace('+', '%20', $encoded_filename);
		if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
		    header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
		} else if (preg_match('/Firefox/', $_SERVER['HTTP_USER_AGENT'])) {
		    header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');
		} else {
		    header('Content-Disposition: attachment; filename="' . $filename . '"');
		}
		header("Content-Length: ". $content_length);
	}
	
	public static function client_ip () {
		if ($HTTP_SERVER_VARS['HTTP_CLIENT_IP']) {
			$ip = $HTTP_SERVER_VARS['HTTP_CLIENT_IP'];
		} elseif ($HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR']) {
			$ip = $HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'];
		} elseif ($HTTP_SERVER_VARS['REMOTE_ADDR']) {
			$ip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
		} elseif (getenv('HTTP_CLIENT_IP')) {
			$ip = getenv('HTTP_CLIENT_IP');
		} elseif (getenv('HTTP_X_FORWARDED_FOR')) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif (getenv('REMOTE_ADDR')) {
			$ip = getenv('REMOTE_ADDR');
		} else {
			$ip = '';
		}
		return $ip;
	}
	
	public static function get_admin_ids () {
		return explode(',', _SUDO_USER_IDS);
	}
	
	public static function csvEncode ($csv) {
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'Mac OS X')) return $csv;
		else return iconv('UTF-8', 'GBK//IGNORE', $csv);
	}
	
	/**
	 * 将数据写到excel中并提示下载。
	 * 执行后会终止程序。
	 * @param array $data 数据，格式见 etc/excel_data_example.php
	 * @param string $file 下载时提示保存的文件名，不支持中文
	 * @return null
	 */
	public static function to_excel ($data, $file = null) {
		//TODO @ 让下载的文件支持保存时提示中文
		if (!$data['title']) return false;
		if (!$data['data']) return false;
		if (!$file) $file = $data['title'].'.xlsx';
		$data_title = array_keys($data['data']);

		require_once ROOT.'/web/lib/PHPExcel/PHPExcel.php';
		
		$excel = new PHPExcel(); // 创建Excel
		$sheet = $excel->getActiveSheet(); // 指定工作表
		$sheet->mergeCellsByColumnAndRow(0, 1, count($data['data']) - 1, 1);
		$sheet->setCellValueByColumnAndRow(0, 1, $data['title']);
		$sheet->getStyleByColumnAndRow(0, 1)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$sheet->getStyleByColumnAndRow(0, 1)->getFont()->setSize(20);
		foreach ($data_title as $k => $title) {
			$sheet->setCellValueByColumnAndRow($k, 2, $title);
		}
		$col = 0;
		foreach ($data['data'] as $v) {
			$row = 3;
			foreach ($v as $d) {
				$sheet->setCellValueByColumnAndRow($col, $row, $d);
				$row++;
			}
			$col++;
		}
		for ($i = 0, $n = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn()); $i <= $n; $i++) {
			$sheet->getColumnDimensionByColumn($i)->setAutoSize(true);
		}
		$_file = TMP.'/report.xlsx.'.microtime(true);
		PHPExcel_IOFactory::createWriter($excel, 'Excel2007')->save($_file);
		G::downloadHeader($file, filesize($_file));
		readfile($_file);
		unlink($_file);
		exit();
	}
	
	/**
	 * 发送邮件。<br>
	 * 配置为string，内容为 '{host}, {port}, {secure:ssl/tls}, {username}, {password}, {address}, {name}'<br>
	 * 配置可以定义再常量里，用时取出即可
	 * @param stirng $config 发送邮件的邮箱配置，格式为：'{host}, {port}, {secure:ssl/tls}, {username}, {password}, {address}, {name}'
	 * @param string $to 多个邮箱用“,”分割
	 * @param string $subject 主题
	 * @param string $body 内容
	 * @return boolean 邮件是否发送成功
	 */
	public static function send_mail ($config, $to, $subject, $body) {
		$conf = array();
		list ($conf['host'], $conf['port'], $conf['secure'], $conf['username'], $conf['password'], $conf['address'], $conf['name']) = explode(',', $config);
		foreach ($conf as $k => $v) $conf[$k] = trim($v);
		
		require_once ROOT . '/lib/phpmailer/class.phpmailer.php';
		
		$mail = new PHPMailer();
		$mail->Mailer = 'smtp'; // 使用smtp方式发送邮件
		$mail->PluginDir = ROOT . '/lib/phpmailer/';
		$mail->Host = $conf['host'];
		$mail->Port = $conf['port'];
		$mail->SMTPAuth = true;
		$mail->SMTPSecure = $conf['secure']; // ssl
		$mail->CharSet = 'UTF-8';
		$mail->IsHTML(true);
		$mail->Username = $conf['username'];
		$mail->Password = $conf['password'];
		$mail->SetFrom($conf['address'], $conf['name']);
		foreach (explode(',', $to) as $t) $mail->AddAddress(trim($t));
		$mail->Subject = $subject;
		$mail->Body = $body;
		$status = $mail->Send();
		$mail->SmtpClose(); // 关闭邮件服务器连接
		return $status;
	}
	
	/**
	 * 分页信息
	 * @param int $total_row
	 * @param int $pagesize
	 * @return array
	 */
	public static function pagination ($total_row, $pagesize = null) {
		if ($pagesize == null && defined('PAGESIZE')) $pagesize = PAGESIZE;
		$total_page = $total_row == 0 ? 1 : ceil($total_row / $pagesize);
		$page = isset($_GET['p']) && filter_var($_GET['p'], FILTER_VALIDATE_INT) ? intval($_GET['p']) : 1;
		if ($page < 1 || $page > $total_page) $page = 1;
		$uris = parse_url($_SERVER['REQUEST_URI']);
		if (!isset($uris['query'])) $uris['query'] = '';
		$uris['query_arr'] = array();
		parse_str($uris['query'], $uris['query_arr']);
		$uris['query_arr']['p'] = '.page.';
		$uris['query'] = http_build_query($uris['query_arr']);
		$uri = $uris['path'] . '?' . $uris['query'];
		$page_info = array(
				'total_row' => $total_row,
				'page' => $page,
				'pagesize' => $pagesize,
				'total_page' => $total_page,
				'uri' => $uri
		);
		return $page_info;
	}
	
	/**
	 * 初始化SQOSS并返回实例
	 * @return SQOSS
	 */
	public static function get_oss () {
		if (!self::$oss) {
			require_once ROOT.'/lib/oss/SQOSS.class.php';
			self::$oss = new OSS();
			self::$oss->setBucket(OSS_ACCESS_BUCKET);
			self::$oss->setObjectPath(OSS_ACCESS_OBJECT_PATH);
		}
		return self::$oss;
	}
	
	public static function toClient($json){
		echo json_encode($json);
		exit;
	}
	
	public function checkToken($time, $token){
		$now = time()*1000;
		if(($now-$time)>86400000)return false;
		
		$s = substr($token, 0, 48);
		$e = substr($token, 48);

		$newToken = $e.$s;
		
		$m = '';
		for($i=0;$i<strlen($newToken);$i++){
			if($i%3==0)$m.=$newToken[$i];
		}

		$md5 = md5($time);

		if($md5!=$m)return false;
		return true;
	}

}
